<script setup lang="ts">
import type { NodejsEnvStore } from "@/modules/dev-env/nodejs/nodejs-env-store.ts";
import type { NpmConfig } from "@/modules/dev-env/nodejs/types.ts";
import { computed, onMounted, reactive } from "vue";
import { electronBuilderBinariesMirrorList, electronMirrorList, npmRegistryList, pythonMirrorList } from "@/modules/dev-env/nodejs/data.ts";
import { CodeOutlined, QuestionCircleOutlined } from "@ant-design/icons-vue";
import { NpmrcFile } from "@/modules/dev-env/nodejs/npmrc-file.ts";
import { hc } from "@/framework/vue/util/render.ts";
import PendingButton from "@/components/framework/pending-button.vue";
import path from "@/framework/util/path.ts";
import { execInTerminal } from "@/util/system-utils2.ts";
import { message } from "ant-design-vue";
import { useLocalShallowRef } from "@/framework/vue/hooks/state.ts";

const { store } = defineProps<{
  store: NodejsEnvStore;
}>();

const npmrcFile = new NpmrcFile();

const formState = reactive<NpmConfig>({
  registry: "",
  electronMirror: "",
  electronBuilderBinariesMirror: "",
  pythonMirror: "",
});

onMounted(async () => {
  await npmrcFile.load();
  formState.registry = npmrcFile.get("registry");
  formState.electronMirror = npmrcFile.get("electron_mirror");
  formState.electronBuilderBinariesMirror = npmrcFile.get("electron_builder_binaries_mirror");
  formState.pythonMirror = npmrcFile.get("python_mirror");
});

const saveNpmConfig = async () => {
  npmrcFile.set("registry", formState.registry);
  npmrcFile.set("electron_mirror", formState.electronMirror);
  npmrcFile.set("electron_builder_binaries_mirror", formState.electronBuilderBinariesMirror);
  npmrcFile.set("python_mirror", formState.pythonMirror);
  await npmrcFile.save();
};

const execCorepack = async (c: string) => {
  const cwd = store.selectedItem!.installPath;
  const corepackCmd = path.join(cwd, "corepack" + (native.process.platform === "win32" ? ".cmd" : ""));
  if (await native.fs.exists(corepackCmd)) {
    await native.cp.execCmd(`corepack ${c}`, { cwd: cwd });
    message.success("已启用corepack");
  } else {
    message.error("未找到corepack命令或版本不支持");
  }
};

const myGlobalTools = useLocalShallowRef("nodejs.global.myTools", "");
const canInstallGlobalTools = computed<boolean>(() => !!store.selectedItem && !!myGlobalTools.value && myGlobalTools.value.trim().length > 0);
const installGlobalTools = async () => {
  const packages = myGlobalTools.value
    .trim()
    .split(/[\n;]/)
    .filter(it => !!it);
  const cwd = store.selectedItem!.installPath;
  execInTerminal(`npm i -g ${packages.join(" ")}`, { cwd: cwd });
};
</script>

<template>
  <a-divider orientation="left">
    <span class="color-text-secondary font-14">npm设置</span>
  </a-divider>
  <a-form-item label="registry">
    <a-auto-complete v-model:value="formState.registry" :options="npmRegistryList" spellcheck="false" />
  </a-form-item>
  <a-form-item>
    <template #label>
      <div>
        <span class="mr-3">electron_mirror</span>
        <a-tooltip title="Electron二进制包下载加速镜像地址" :mouse-leave-delay="0" placement="left">
          <QuestionCircleOutlined />
        </a-tooltip>
      </div>
    </template>
    <a-auto-complete v-model:value="formState.electronMirror" :options="electronMirrorList" spellcheck="false" />
  </a-form-item>
  <a-form-item>
    <template #label>
      <div>
        <span class="mr-3">electron_builder_binaries_mirror</span>
        <a-tooltip title="Electron构建工具下载加速镜像地址" :mouse-leave-delay="0" placement="left">
          <QuestionCircleOutlined />
        </a-tooltip>
      </div>
    </template>
    <a-auto-complete v-model:value="formState.electronBuilderBinariesMirror" :options="electronBuilderBinariesMirrorList" spellcheck="false" />
  </a-form-item>
  <a-form-item>
    <template #label>
      <div>
        <span class="mr-3">python_mirror</span>
        <a-tooltip title="Python下载加速镜像地址" :mouse-leave-delay="0" placement="left">
          <QuestionCircleOutlined />
        </a-tooltip>
      </div>
    </template>
    <a-auto-complete v-model:value="formState.pythonMirror" :options="pythonMirrorList" spellcheck="false" />
  </a-form-item>

  <a-form-item label=" " :colon="false">
    <a-button class="w-150" @click="saveNpmConfig">保存</a-button>
  </a-form-item>

  <a-divider orientation="left">
    <span class="color-text-secondary font-14"
      >其他设置
      <template v-if="store.selectedItem">(v{{ store.selectedItem.version }})</template>
    </span>
  </a-divider>
  <a-form-item label="corepack" help="安装新版本nodejs后需要重新执行">
    <a-space>
      <pending-button :disabled="!store.selectedItem" :icon="hc(CodeOutlined)" show-error-message :fn="execCorepack" fn-args="enable"
        >enable</pending-button
      >
      <pending-button :disabled="!store.selectedItem" :icon="hc(CodeOutlined)" show-error-message :fn="execCorepack" fn-args="disable"
        >disable</pending-button
      >
    </a-space>
  </a-form-item>
  <a-form-item label="全局工具安装" help="npm i -g xxx，多个以分号或换行隔开，安装新版本nodejs后需要重新安装">
    <a-textarea v-model:value="myGlobalTools" :auto-size="{ minRows: 5, maxRows: 5 }" />
  </a-form-item>
  <a-form-item label=" " :colon="false">
    <a-button :icon="hc(CodeOutlined)" :disabled="!canInstallGlobalTools" @click="installGlobalTools">安装全局工具</a-button>
  </a-form-item>
</template>
